package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ev.common.enums.AuditStatusDict;
import com.ev.custom.dao.FacilityLocationDao;
import com.ev.custom.domain.FacilityDO;
import com.ev.custom.domain.FacilityLocationDO;
import com.ev.custom.service.FacilityLocationService;
import com.ev.custom.service.FacilityService;
import com.ev.framework.utils.R;
import com.ev.framework.utils.ShiroUtils;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3StockPlaceSynService;
import com.ev.k3cloudBusiness.vo.K3StockPlaceResultsVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class K3StockPlaceSynServiceImpl implements K3StockPlaceSynService {
    @Autowired
    FacilityLocationDao      facilityLocationDao;
    @Autowired
    FacilityLocationService  facilityLocationService;
    @Autowired
    FacilityService          facilityService;
    @Autowired
    kingdeeMiddlewareService kingdeeMiddlewareService;

    @Override
    public R StockPlace() {
        //查询芯软云仓库
        List<FacilityDO> facilityDOList = facilityService.listAll();
        //查询芯软云仓位
        List<FacilityLocationDO> facilityLocationDOList = facilityLocationService.listAll();
        //调用K3Cloud中间件接口查询启用的仓位
        String stockPlaceResult = kingdeeMiddlewareService.StockPlaceAll();
        JSONObject resultObj = JSON.parseObject(stockPlaceResult);
        if (!resultObj.getString("code").equals("0")) {
            log.info(resultObj.getString("msg"));
            return R.error(resultObj.getString("msg"));
        }
        List<K3StockPlaceResultsVo> k3StockPlaceResultsVos = JSON
            .parseArray(resultObj.get("data").toString(), K3StockPlaceResultsVo.class);

        if (k3StockPlaceResultsVos.size() > 0) {
            long okAudit = AuditStatusDict.OK_AUDIT.getId();
            Long userId = ShiroUtils.getUserId();
            // 本地仓位代码
            List<Long> localIdList = facilityLocationDOList.stream().map(FacilityLocationDO::getId)
                    .collect(Collectors.toList());
            // K3Cloud仓位代码
            List<Long> remoteIdList = k3StockPlaceResultsVos.stream().map(K3StockPlaceResultsVo::getId)
                    .collect(Collectors.toList());
            // 删除的 k3无，本地有
            List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e))
                    .collect(Collectors.toList());
            // 修改的（本地库有的，远端库有的）
            List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains)
                    .collect(Collectors.toList());
            // 新增的（本地库无的，远端库有的）
            remoteIdList.removeAll(updateIdList);
            if (deleteIdList.size() > 0) {
                //批量删除
                List<FacilityLocationDO> facilityLocationDOS = facilityLocationDOList.stream()
                        .filter(e -> deleteIdList.contains(e.getId())).collect(Collectors.toList());
                for (FacilityLocationDO facilityDOS : facilityLocationDOS) {
                    facilityDOS.setDelFlag(1);
                }
                facilityLocationService.batchUpdate(facilityLocationDOS);
                log.info("批量删除");
            }
            if (updateIdList.size() > 0) {
                //批量更新
                List<K3StockPlaceResultsVo> stockPlaceResultsVoList = k3StockPlaceResultsVos.stream()
                        .filter(e -> updateIdList.contains(e.getId())).collect(Collectors.toList());
                List<FacilityLocationDO> facilityLocationDOS = facilityLocationDOList.stream()
                        .filter(e -> updateIdList.contains(e.getId())).collect(Collectors.toList());
                for (FacilityLocationDO facilityLocationDO : facilityLocationDOS) {
                    K3StockPlaceResultsVo stockPlaceResultsVo = stockPlaceResultsVoList.stream()
                            .filter(e -> (facilityLocationDO.getId().equals(e.getId())))
                            .collect(Collectors.toList()).get(0);
                    //仓位名称
                    facilityLocationDO.setName(stockPlaceResultsVo.getName());
                    //仓位代码
                    facilityLocationDO.setSerialNo(stockPlaceResultsVo.getNumber());
                    List<FacilityDO> facilityDO = facilityDOList.stream()
                            .filter(e -> e.getId().equals(stockPlaceResultsVo.getStockId()))
                            .collect(Collectors.toList());
                    if (facilityDO.size() == 0) {
                        return R.error(stockPlaceResultsVo.getStockNumber() + "仓库不存在,请先同步");
                    }
                    //仓库ID
                    facilityLocationDO.setFacilityId(stockPlaceResultsVo.getStockId());
                    //                facilityLocationDO.setStockUseid(stockPlaceResultsVo.ge());
                    facilityLocationDO.setAuditor(userId);
                }
                facilityLocationService.batchUpdate(facilityLocationDOS);
                log.info("批量更新");
            }
            if (remoteIdList.size() > 0) {
                //批量插入
                List<K3StockPlaceResultsVo> stockResulitsVos = k3StockPlaceResultsVos.stream()
                        .filter(e -> remoteIdList.contains(e.getId())).collect(Collectors.toList());
                List<FacilityLocationDO> facilityLocationDOS = Lists.newArrayList();
                for (K3StockPlaceResultsVo stockPlaceResultsVo : stockResulitsVos) {
                    FacilityLocationDO facilityLocationDO = new FacilityLocationDO();
                    List<FacilityDO> facilityDOS = facilityDOList.stream()
                            .filter(e -> e.getId().equals(stockPlaceResultsVo.getStockId()))
                            .collect(Collectors.toList());
                    facilityLocationDO.setId(stockPlaceResultsVo.getId());
                    //仓位姓名
                    facilityLocationDO.setName(stockPlaceResultsVo.getName());
                    //仓位代码
                    facilityLocationDO.setSerialNo(stockPlaceResultsVo.getNumber());
                    if (facilityDOS.size() == 0) {
                        return R.error(stockPlaceResultsVo.getStockNumber() + "仓库不存在,请先同步");
                    }
                    facilityLocationDO.setFacilityId(stockPlaceResultsVo.getStockId());
                    //                facilityLocationDO.setStockUseid(stockPlaceResultsVo.getSTOCKUSEID());
                    facilityLocationDO.setDelFlag(0);
                    facilityLocationDO.setAuditSign(okAudit);
                    facilityLocationDO.setAuditor(userId);
                    facilityLocationDOS.add(facilityLocationDO);
                }
                facilityLocationService.batchSave(facilityLocationDOS);
                log.info("批量新增");
            }
        }
        return R.ok();
    }
}
